import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { Dispatch } from "redux";

const countStore = createSlice({
    name: 'counter',
    // 初始化数据
    initialState: {
        count: 10
    },
    // 定义修改数据方法
    reducers: {
        add(state) {
            state.count ++
        },
        // 传参
        jian(state,action) {
            state.count -= action.payload
        },
        // 异步请求
        getCount(state,action) {
            state.count = action.payload
        }
    }
})

// actions解构
const { add, jian, getCount } = countStore.actions

// 异步请求
const fetchGetCount = () => {
    return async() => {
        const res =await axios.get('/地址')
        getCount(res.data)
    }
}
const fetchGetCount1 = (dispatch: Dispatch) => {
    return async() => {
        const res =await axios.get('/地址')
        dispatch(getCount(res.data))
    }
}

// 获取reducer函数
const countReducer = countStore.reducer

// 导出actions函数对象
export { add, jian, fetchGetCount, fetchGetCount1 }

// 导出reducer函数
export default countReducer


